<?php
/**
 * 产品分类管理
 * @author cjli
 *
 */
class CategoryAction extends AdminAction
{
	public function _initialize()
	{
		parent::_initialize();
		$this->_vid = intval($_GET['vid']);
		if( $this->_vid == 0 ){
			$this->_vid = CategoryModel::TYPE_CATEGORY;
		}
		$vocaList = CategoryModel::getVocabularyList();
		$this->_vocabulary_name = $vocabulary_name =  $vocaList[$this->_vid];
		$this->assign('vocabulary_name', $vocabulary_name);
		$this->assign('vid', $this->_vid);
		$this->assign('jumpUrl', U('category/index', 'vid='.$this->_vid));
	}
	
	public function index()
	{
		import('COM.Tree');
		$tree = new Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		$array = array();
		$catdb = M('category');
		if( $this->_vid == CategoryModel::TYPE_CATEGORY ){
			$modelList = AttributeModel::getModelList();//属性类型列表
		}
		
		//分类列表
		$categoryList = CategoryModel::getCategoryList($this->_vid);

		foreach ($categoryList as $r)
		{
			$r['display_icon'] = $r['display'] ? '<font color="red">√</font>' : '<font color="blue">×</font>';
			$r['str_manage'] = '';
			if( $this->_vid == CategoryModel::TYPE_CATEGORY || $this->_vid == CategoryModel::TYPE_ARTICLE ){
				$r['str_manage'] .= '<a href="'.U('category/add', array('vid'=>$this->_vid,'catid'=>$r['id'])).'">添加子类</a> | ';
			}
			
			$r['str_manage'] .= '<a href="'.U('category/edit', array('vid'=>$this->_vid,'catid'=>$r['id'])).'">修改</a> | ';
			$r['str_manage'] .= '<a href="javascript:confirmurl(\''.U('category/delete', array('vid'=>$this->_vid,'catid'=>$r['id'])).'\',\'确认要删除 『'.trim($r['name']).' 』 吗？\')">删除</a> | ';
			$url = "http://". $_SERVER['HTTP_HOST']."/category/".$r['id']."-all";
			$r['str_manage'] .= '<a href="'.$url.'" target="_blank">预览</a>';
			$array[] = $r;
		}
		
		$str  = "<tr>
					<td align='center'><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input-text-c'></td>
					<td align='center'>\$id</td>
					<td >\$spacer\$name</td>
					";
		$str  .= "<td align='center'>\$display_icon</td>
					<td align='center' >\$str_manage</td>
				</tr>";
		$tree->init($array);
		$categorys = $tree->get_tree(0, $str);
		$this->assign('categorys', $categorys);
		$this->display('category_list');
	}
	
	public function add()
	{
		$catdb = M('category');
		if(isset($_POST['dosubmit'])){
			//上传图片 +每种语言的图片
			$languageList = SiteModel::getLanguageList();
			$is_items_img = false;
            foreach($languageList as $key=>$value){
                if ((isset($_FILES['cat_upimage_'.$key]) && $_FILES['cat_upimage_'.$key]['name']) 
                	|| (isset($_FILES['cat_upimage_adv_'.$key]) && $_FILES['cat_upimage_adv_'.$key]['name'])){
                    $is_items_img = true;
                    break;
                }
            }
			if ((isset($_FILES['upimage']) && $_FILES['upimage']['name']) || (isset($_FILES['upimage_adv']) && $_FILES['upimage_adv']['name']) || $is_items_img){
				$info = $this->upload('category');
				if(is_array($info)) {// 上传成功 获取上传文件信息
					if($info['upimage']){
						$_POST['img'] = UPLOAD_PATH . $info['upimage']['savename'];
					}
					if($info['upimage_adv']){
						$_POST['adv_img'] = UPLOAD_PATH . $info['upimage_adv']['savename'];
					}
					//每种语言的图片
					foreach($languageList as $key=>$value){
                        if($info['cat_upimage_'.$key]){
                            $_POST['category'][$key]['items_img'] = UPLOAD_PATH . $info['cat_upimage_'.$key]['savename'];
                        }
                        if($info['cat_upimage_adv_'.$key]){
                            $_POST['category'][$key]['items_adv_img'] = UPLOAD_PATH . $info['cat_upimage_adv_'.$key]['savename'];
                        }
					}
				}else{
					$this->error($info);
				}
			}
			$_POST['vid'] = $this->_vid;
			
			//分类入库
			$category_id = CategoryModel::updateCategoryInfo($_POST);
			
			if($category_id){
				//更新语言选项
				CategoryModel::updateCategoryItems($_POST['category'], $category_id);
				
				S('admin_category_list_base_'.$this->_vid, NULL);
				$this->success($this->_vocabulary_name.'添加成功！');
			}else{
				$this->error($this->_vocabulary_name.'添加失败！');
			}
		}else{
			if( $this->_vid == CategoryModel::TYPE_CATEGORY ){
				$modelList = AttributeModel::getModelList(); //属性类型列表
				$this->assign('modelList', $modelList);
				$attr_list = $this->get_attr_list();
				$this->assign('attr_list', $attr_list);
				$filter_attr_id = 0;
				$this->assign('filter_attr_id', $filter_attr_id);
			}

			if( $this->_vid == CategoryModel::TYPE_CATEGORY || $this->_vid == CategoryModel::TYPE_ARTICLE ){
				$parentId = isset($_GET['catid']) ? intval($_GET['catid']) : 0;
				$select_categorys = CategoryModel::categorySelectList($parentId, $this->_vid); //下拉分类
				$this->assign('select_categorys', $select_categorys);
			}
			$this->display('category_form');
		}
	}
	
	public function edit()
	{
		$catdb = D('category');
		$category_id = intval($_GET['catid']);
		$catInfo = $catdb->where('id='.$category_id)->find();
		if(is_null($catInfo)){
			$this->error('编辑'.$this->_vocabulary_name.'不存在!');
		}
		
		if(isset($_POST['dosubmit']))
		{
			//上传图片 +每种语言的图片
			$languageList = SiteModel::getLanguageList();
			$is_items_img = false;
            foreach($languageList as $key=>$value){
                if ((isset($_FILES['cat_upimage_'.$key]) && $_FILES['cat_upimage_'.$key]['name']) 
                	|| (isset($_FILES['cat_upimage_adv_'.$key]) && $_FILES['cat_upimage_adv_'.$key]['name'])){
                    $is_items_img = true;
                    break;
                }
            }
			if ((isset($_FILES['upimage']) && $_FILES['upimage']['name']) || (isset($_FILES['upimage_adv']) && $_FILES['upimage_adv']['name']) || $is_items_img){
				$info = $this->upload('category');
				if(is_array($info)) {// 上传成功 获取上传文件信息
					if($info['upimage']){
						$_POST['img'] = UPLOAD_PATH . $info['upimage']['savename'];
					}
					if($info['upimage_adv']){
						$_POST['adv_img'] = UPLOAD_PATH . $info['upimage_adv']['savename'];
					}
					//每种语言的图片
					foreach($languageList as $key=>$value){
                        if($info['cat_upimage_'.$key]){
                            $_POST['category'][$key]['items_img'] = UPLOAD_PATH . $info['cat_upimage_'.$key]['savename'];
                        }
                        if($info['cat_upimage_adv_'.$key]){
                            $_POST['category'][$key]['items_adv_img'] = UPLOAD_PATH . $info['cat_upimage_adv_'.$key]['savename'];
                        }
					}
				}else{
					$this->error($info);
				}
			}
			$_POST['vid'] = $this->_vid;
			
			//分类入库
			$category_id = CategoryModel::updateCategoryInfo($_POST, $category_id);
			if($category_id){
				//更新分类详细
				CategoryModel::updateCategoryItems($_POST['category'], $category_id);
				S('admin_category_list_base_'.$this->_vid, NULL);
				$this->success($this->_vocabulary_name.'编辑成功！');
			}else{
				$this->error($this->_vocabulary_name.'编辑失败！');
			}
		}else{
			$catInfo['items'] = CategoryModel::getCategoryItems($category_id);
			
			if( $this->_vid == CategoryModel::TYPE_CATEGORY ){
				$modelList = AttributeModel::getModelList(); //属性类型列表
				$this->assign('modelList', $modelList);
				$attr_list = $this->get_attr_list();
				$this->assign('attr_list', $attr_list);
				
				$filter_attr_list = array();
				if ($catInfo['filter_attr'])
		    {
		        $filter_attr = explode(",", $catInfo['filter_attr']);  //把多个筛选属性放到数组中

		        $attr_db = D('attribute');
		        foreach ($filter_attr AS $k => $v)
		        {
		        		$model_id = $attr_db->where(array('attr_id' => intval($v)))->getField('model_id');
		            $filter_attr_list[$k]['model_id'] = $model_id;  //取得每个属性的商品类型
		            $filter_attr_list[$k]['attr_id'] = $v;
		            $attr_option = array();
		
		            foreach ($attr_list[$model_id] as $val)
		            {
		                $attr_option[key($val)] = current ($val);
		            }
		            $filter_attr_list[$k]['option'] = $attr_option;
		        }
		        $filter_attr_id = 1;
		    }
		    else
		    {
		        $filter_attr_id = 0;
		    }
				$this->assign('filter_attr_id', $filter_attr_id);
				$this->assign('filter_attr_list', $filter_attr_list);
			}
//			dump($filter_attr_list);exit;
			if( $this->_vid == CategoryModel::TYPE_CATEGORY || $this->_vid == CategoryModel::TYPE_ARTICLE ){
				$select_categorys = CategoryModel::categorySelectList($catInfo['parentid'], $this->_vid); //下拉分类
				$this->assign('select_categorys', $select_categorys);
			}
			$category_id = explode(",",$catInfo['category_id']);
			$this->assign('category_id', $category_id);
			$colour_id = explode(",",$catInfo['colour_id']);
			$this->assign('colour_id', $colour_id);
			$this->assign('cat', $catInfo);
			$this->display('category_form');
		}
	}
	
	public function delete()
	{
		$category_id = intval($_GET['catid']);
		$catdb = D('category');
		$count = $catdb->where(array('parentid'=>$category_id))->count();
		if($count){
			$this->error('此分类下还有子类，请先删除子类！');
		}else{
			CategoryModel::deleteCategory($category_id); //删除分类
			S('admin_category_list_base_'.$this->_vid, NULL);
			$this->success($this->_vocabulary_name.'删除成功！');
		}
	}
	
	public function listorder()
	{
		if(isset($_POST['dosubmit'])) {
			$catdb = D('category');
			foreach($_POST['listorders'] as $id => $listorder) {
				$catdb->where(array('id'=>$id))->save(array('listorder'=>$listorder));
			}
			S('admin_category_list_base_'.$this->_vid, NULL);
			$this->success('排序操作成功！');
		} else {
			$this->error('排序操作失败！');
		}
	}
	
	//ajax检验分类是否已经存在
	public function public_checkname_ajx()
	{
		$catname = trim($_GET['catname']);
		$catid = intval($_GET['catid']);
		$catdb = D('category');
		$where['name'] = $catname;
		$where['vid'] = $this->_vid;
		if($catid){
			$where['id'] = array('neq',$catid);
		}
		$rs = $catdb->where($where)->getField('id');
		if(is_null($rs)){
			exit('1');
		}
		exit('0');
	}
	
	/**
	 * 获取属性列表
	 *
	 * @access  public
	 * @param
	 *
	 * @return void
	 */
	private function get_attr_list()
	{
		$attr_db = D('attribute');
	    $sql = "SELECT a.attr_id, a.model_id, a.attr_name FROM attribute AS a, model AS c ".
	    "WHERE a.model_id = c.id AND a.attr_index=1 ORDER BY a.model_id , a.sort_order";
	    $arr = $attr_db->query($sql);

	    $list = array();
	
	    foreach ($arr as $val)
	    {
	        $list[$val['model_id']][] = array($val['attr_id']=>$val['attr_name']);
	    }
	    return $list;
	}
	
	//ajax获取分类属性
	public function type_style_ajx()
	{
		$tid = $_REQUEST['tid'];
		$catdb = D('category');
		$catInfo = $catdb->where('id='.$tid)->find();
		$result = array(
			'error' => 1,
			'category_list' => null,
			'colour_list' => null,
		);
		$html = '';
		$html2 = '';
		if($catInfo){
			if($catInfo['parentid']>0){
				$catInfo2 = $catdb->where('id='.$catInfo['parentid'])->find();
				$category_id = explode(",",$catInfo2['category_id']);
				$colour_id = explode(",",$catInfo2['colour_id']);
				foreach ($category_id as $category){
					$category_name = CategoryModel::getCategoryItems($category, C('language_id')); 
					if($category_name){
						$html .='<input type="checkbox" name="categoryId[]" value="'.$category.'" />'.$category_name[C('language_id')]['name'].'';
					}
					
				}
				foreach ($colour_id as $colour){
					$colour_name = CategoryModel::getCategoryItems($colour, C('language_id')); 
					if($colour_name){
						$html2 .='<input type="checkbox" name="colourId[]" value="'.$colour.'" />'.$colour_name[C('language_id')]['name'].'';
					}
					
				}
			}else{
				$category_id = explode(",",$catInfo['category_id']);
				$colour_id = explode(",",$catInfo['colour_id']);
				foreach ($category_id as $category){
					$category_name = CategoryModel::getCategoryItems($category, C('language_id')); 
					
					if($category_name){
						$html .='<input type="checkbox" name="categoryId[]" value="'.$category.'" />'.$category_name[C('language_id')]['name'].'';
					}
				}
				foreach ($colour_id as $colour){
					$colour_name = CategoryModel::getCategoryItems($colour, C('language_id')); 
					
					if($colour_name){
						$html2 .='<input type="checkbox" name="categoryId[]" value="'.$colour.'" />'.$colour_name[C('language_id')]['name'].'';
					}
				}
			}
			
			$result['error'] = '0';
			$result['category_list'] = $html;
			$result['colour_list'] = $html2;
		}
		echo json_encode($result);exit;
		
	}
	
	/**
	 * 投诉列表
	 */
	private function complaint_list()
	{
		$where = array(
			'parent_id' => 0,
		);
		
		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
		
		$order_complaint_db = D('orders_complaint');
		//分页
		$order_complaint_db->where($where);
		$count = $order_complaint_db->count();//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$order_complaint_db->field('id,order_sn,status,add_time,type,contact_name');
		$order_complaint_db->limit($Page->firstRow.','.$Page->listRows);
		$order_complaint_db->where($where)->order('id DESC');
		$complaintList = $order_complaint_db->select();
		
		$this->assign('complaintList', $complaintList);
		$this->display('complaint_list');
	}
}